/*
 * Copyright 2020 lcnap
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pers.lcnap.simplerpc.rpc.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import pers.lcnap.RpcRequest;
import pers.lcnap.simplerpc.rpc.RpcRequestEvent;
import pers.lcnap.simplerpc.util.MetricUtil;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 启动监听本地 {@link RpcRequest} 请求队列的线程。
 * 线程通过{@link ChannelHandlerContext#fireUserEventTriggered(Object)}触发{@link RpcRequestEvent}事件。
 * 将请求事件转发出去。由 {@link RpcCallChannelHandler} 处理。
 */
public class RpcRequestQueueChannelHandler extends ChannelInboundHandlerAdapter {
    private final ConcurrentLinkedQueue<RpcRequestEvent> queue;

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    public RpcRequestQueueChannelHandler(ConcurrentLinkedQueue<RpcRequestEvent> queue) {
        this.queue = queue;
    }


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        executor.submit((Runnable) () -> {
            while (true) {
                RpcRequestEvent requestEvent = queue.poll();
                if (requestEvent != null) {
                    try {
                        ctx.fireUserEventTriggered(requestEvent);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ctx.fireExceptionCaught(e.getCause());
                    }
                    MetricUtil.rpcRequestSendCount.mark();
                }
            }
        });

    }

}
